import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateStudycontentsortDto } from './dto/create-studycontentsort.dto';
import { UpdateStudycontentsortDto } from './dto/update-studycontentsort.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Studycontentsort } from './entities/studycontentsort.entity';
import { Repository } from 'typeorm';
import { PageResultDto, QueryListDto } from 'src/common/dto';

@Injectable()
export class StudycontentsortService {
  constructor(
    @InjectRepository(Studycontentsort)
    private studycontentsortRepository: Repository<Studycontentsort>,
  ) {}

  async create(createStudycontentsortDto: CreateStudycontentsortDto) {
    const sort = this.studycontentsortRepository.create(
      createStudycontentsortDto,
    );
    await this.studycontentsortRepository.save(sort);
    return '添加学习内容分类成功';
  }
  async findAll(
    querylistDto: QueryListDto,
  ): Promise<PageResultDto<Studycontentsort>> {
    const pageNum = Number(querylistDto.pageNum) || 1;
    const pageSize = Number(querylistDto.pageSize) || 10;

    const [data, total] = await this.studycontentsortRepository
      .createQueryBuilder('contentsort')
      .where('contentsort.Deleted = :deleted', { deleted: 0 })
      .skip((pageNum - 1) * pageSize)
      .take(pageSize)
      .orderBy('contentsort.Id', 'DESC')
      .getManyAndCount();

    const result = new PageResultDto<Studycontentsort>();
    result.data = data;
    result.total = total;
    result.pageNum = pageNum;
    result.pageSize = pageSize;
    return result;
  }

  async findOne(id: number) {
    const item = await this.studycontentsortRepository.findOne({
      where: { Id: String(id), Deleted: 0 },
    });
    if (!item) {
      throw new NotFoundException(`ID 为 ${id} 的学习资源不存在`);
    }
    return item;
  }

  async update(id: number, updateStudycontentDto: UpdateStudycontentsortDto) {
    const existing = await this.studycontentsortRepository.findOne({
      where: { Id: String(id), Deleted: 0 },
    });
    if (!existing) {
      throw new NotFoundException(`ID 为 ${id} 的资源未找到`);
    }
    await this.studycontentsortRepository.save(existing);
    return '更新成功';
  }

  async remove(id: number) {
    const item = await this.studycontentsortRepository.findOne({
      where: { Id: String(id), Deleted: 0 },
    });

    if (!item) {
      throw new NotFoundException(`ID 为 ${id} 的资源未找到或已删除`);
    }
    item.Deleted = 1;
    await this.studycontentsortRepository.save(item);

    return '软删除成功';
  }
}
